﻿/* Copyright (c) 2015 Slava Naumenko - http://m4w.codeplex.com */

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web.Services;

namespace M4W.ASM.Services
{
    [WebService(Namespace = "M4W.ASM.Services")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    [System.ComponentModel.ToolboxItem(false)]
    public class Email : System.Web.Services.WebService
    {
        [WebMethod]
        public string Send(string Subject, string Body, string Append, string From, string To, string Cc)
        {
            string result = "";
            try
            {
                result = EmailSend.Invoke(Subject, Body, Append, From, To, Cc);
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }
            return result;
        }

        [WebMethod]
        public string Mail(string Subject, string Body, string Append, string From, string To, string Cc, string Attachments)
        {
            string result = "";
            try
            {
                result = EmailMail.Invoke(Subject, Body, Append, From, To, Cc, Attachments);
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }
            return result;
        }
    }

    // Invocations

    internal static class EmailSend
    {
        internal static string Invoke(string Subject, string Body, string Append, string From, string To, string Cc)
        {
            string result = "";

            string curl = Helper.GetCurrentUrl();

            using (SPSite site = new SPSite(curl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    StringDictionary headers = new StringDictionary();

                    headers.Add("subject", Subject);
                    string from = From; if (from == "") { from = SPAdministrationWebApplication.Local.OutboundMailSenderAddress; }
                    headers.Add("from", from);
                    headers.Add("to", To);
                    headers.Add("cc", Cc);

                    Mail(web, headers, EmailText.Append(Body, Append));

                    result = "E-mail: '" + Subject + "'; To: " + To + ".";

                    web.AllowUnsafeUpdates = false;
                }
            }

            return result;
        }

        internal static void Mail(SPWeb web, StringDictionary headers, string body)
        {
            SPUtility.SendEmail(web, headers, body);
        }
    }

    internal static class EmailMail
    {
        internal static string Invoke(string Subject, string Body, string Append, string From, string To, string Cc, string Attachments)
        {
            string result = "";

            string curl = Helper.GetCurrentUrl();

            using (SPSite site = new SPSite(curl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    string from = From; if (from == "") { from = SPAdministrationWebApplication.Local.OutboundMailSenderAddress; }
                    MailMessage email = new MailMessage(new MailAddress(from), new MailAddress(To));
                    string[] ccs = Cc.Split(';');
                    foreach (string c in ccs)
                    {
                        if (c.Trim() != "")
                        {
                            email.CC.Add(new MailAddress(c.Trim()));
                        }
                    }
                    email.Subject = Subject;
                    email.Body = EmailText.Append(Body, Append);
                    email.IsBodyHtml = true;

                    string[] atts = Attachments.Split(';');
                    foreach (string att in atts)
                    {
                        if (att.Trim() != "")
                        {
                            SPFile file = web.GetFile(att.Trim());
                            Stream filetStream = file.OpenBinaryStream();
                            Attachment attachment = new Attachment(filetStream, file.Name);
                            email.Attachments.Add(attachment);
                        }
                    }

                    SmtpClient mailServer = new SmtpClient(web.Site.WebApplication.OutboundMailServiceInstance.Server.Address);
                    mailServer.Credentials = CredentialCache.DefaultNetworkCredentials;
                    mailServer.Send(email);

                    result = "E-mail: '" + Subject + "'; To: " + To + ".";

                    web.AllowUnsafeUpdates = false;
                }
            }

            return result;
        }
    }

    internal static class EmailText
    {
        internal static string Append(string body, string append)
        {
            string eBody = "";

            if (body.Contains("%APPEND%"))
            {
                eBody = body.Replace("%APPEND%", append);
            }
            else
            {
                string sBody = "</BODY></HTML>";
                string fBody = "</FONT></SPAN></P>";
                string mBody = body;

                if (mBody.Contains(sBody))
                {
                    mBody = mBody.Replace(sBody, "");

                    if (mBody.Contains(fBody))
                    {
                        mBody = mBody.Remove(mBody.LastIndexOf(fBody), fBody.Length) + append + fBody;
                    }
                    else
                    {
                        mBody = mBody + append;
                    }

                    eBody = mBody + sBody;
                }
                else
                {
                    eBody = mBody + append;
                }
            }

            return eBody;
        }
    }
}